/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * MonitoringForm.java
 *
 * Created on May 7, 2010, 10:26:56 PM
 */

package dkbta.server.gui.forms;

import dkbta.server.domain.cu.CUStub;
import dkbta.server.util.query.Query;
import org.apache.log4j.Logger;

import dkbta.server.domain.Coordinator;
import dkbta.server.gui.Observer;
import dkbta.server.util.query.Query.PlanState;
import java.util.Hashtable;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;




/**
 * @author Arkady Mishiev
 *
 */
public class MonitoringForm extends javax.swing.JFrame implements Observer {
	private static Logger s_logger;	
	private Coordinator m_coordinator;
        /*<planId,rowIndex>*/
        private Hashtable<String,Integer> m_plansIdMap;
        /*<unitId,rowIndex>*/
        private Hashtable<String,Integer> m_unitsIdMap;
        private int m_totalPlanRows;
        private int m_totalUnitRows;
	
    /** Creates new form MonitoringForm */
    public MonitoringForm() {
        initComponents();
    }
    
    public MonitoringForm(Coordinator coordinator) {
    	this();
		s_logger = Logger.getLogger(MonitoringForm.class);
		m_coordinator = coordinator;
		m_coordinator.addQueriesPanelObserver(this);
		m_coordinator.addCUPanelObserver(this);
		m_coordinator.addLogsPanelObserver(this);
		
		m_logsTextArea.setEditable(false);
                m_plansIdMap = new Hashtable<String, Integer>();
                m_unitsIdMap = new Hashtable<String, Integer>();
                m_totalPlanRows = 0;
                m_totalUnitRows = 0;
		m_logsTextArea.append("waiting to start server \n");
		this.setVisible(true);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        m_queriesPanel = new javax.swing.JPanel();
        jScrollPane2 = new javax.swing.JScrollPane();
        m_plansJTable = new javax.swing.JTable();
        m_CUPanel = new javax.swing.JPanel();
        jScrollPane3 = new javax.swing.JScrollPane();
        unitsJTable = new javax.swing.JTable();
        m_logsPanel = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        m_logsTextArea = new javax.swing.JTextArea();
        monitorJMenuBar = new javax.swing.JMenuBar();
        jMenu1 = new javax.swing.JMenu();
        m_startCoordinatorMenuItem = new javax.swing.JMenuItem();
        m_stopCoordinatorMenuItem = new javax.swing.JMenuItem();
        m_exitMenuItem = new javax.swing.JMenuItem();
        jMenu2 = new javax.swing.JMenu();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Server DKBTA");
        setMinimumSize(new java.awt.Dimension(600, 489));

        m_queriesPanel.setBorder(javax.swing.BorderFactory.createTitledBorder("Plans"));

        m_plansJTable.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Plan ID", "Client ID", "State", "Start", "Finish "
            }
        ) {
            Class[] types = new Class [] {
                java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, false, false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jScrollPane2.setViewportView(m_plansJTable);

        javax.swing.GroupLayout m_queriesPanelLayout = new javax.swing.GroupLayout(m_queriesPanel);
        m_queriesPanel.setLayout(m_queriesPanelLayout);
        m_queriesPanelLayout.setHorizontalGroup(
            m_queriesPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(m_queriesPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        m_queriesPanelLayout.setVerticalGroup(
            m_queriesPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(m_queriesPanelLayout.createSequentialGroup()
                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 289, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        m_CUPanel.setBorder(javax.swing.BorderFactory.createTitledBorder("Units"));

        unitsJTable.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Unit ID", "Plan ID", "State", "Start", "Finish"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, false, false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jScrollPane3.setViewportView(unitsJTable);

        javax.swing.GroupLayout m_CUPanelLayout = new javax.swing.GroupLayout(m_CUPanel);
        m_CUPanel.setLayout(m_CUPanelLayout);
        m_CUPanelLayout.setHorizontalGroup(
            m_CUPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(m_CUPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 469, Short.MAX_VALUE)
                .addContainerGap())
        );
        m_CUPanelLayout.setVerticalGroup(
            m_CUPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(m_CUPanelLayout.createSequentialGroup()
                .addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 289, Short.MAX_VALUE)
                .addContainerGap())
        );

        m_logsPanel.setBorder(javax.swing.BorderFactory.createTitledBorder("Logs"));
        m_logsPanel.setLayout(new java.awt.BorderLayout());

        m_logsTextArea.setColumns(20);
        m_logsTextArea.setRows(5);
        jScrollPane1.setViewportView(m_logsTextArea);

        m_logsPanel.add(jScrollPane1, java.awt.BorderLayout.CENTER);

        jMenu1.setText("File");

        m_startCoordinatorMenuItem.setText("Start");
        m_startCoordinatorMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                m_startCoordinatorMenuItemActionPerformed(evt);
            }
        });
        jMenu1.add(m_startCoordinatorMenuItem);

        m_stopCoordinatorMenuItem.setText("Stop");
        jMenu1.add(m_stopCoordinatorMenuItem);

        m_exitMenuItem.setText("Exit");
        jMenu1.add(m_exitMenuItem);

        monitorJMenuBar.add(jMenu1);

        jMenu2.setText("Edit");
        monitorJMenuBar.add(jMenu2);

        setJMenuBar(monitorJMenuBar);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(m_logsPanel, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 991, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(m_queriesPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(m_CUPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(m_CUPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(m_queriesPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addGap(18, 18, 18)
                .addComponent(m_logsPanel, javax.swing.GroupLayout.DEFAULT_SIZE, 217, Short.MAX_VALUE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void m_startCoordinatorMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_m_startCoordinatorMenuItemActionPerformed
        // TODO add your handling code here:
        new Thread(m_coordinator,"Coordinator").start();
        m_startCoordinatorMenuItem.setEnabled(false);
    }//GEN-LAST:event_m_startCoordinatorMenuItemActionPerformed

    /**
    * @param args the command line arguments
    */
//    public static void main(String args[]) {
//        java.awt.EventQueue.invokeLater(new Runnable() {
//            public void run() {
//                new MonitoringForm().setVisible(true);
//            }
//        });
//    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JMenu jMenu1;
    private javax.swing.JMenu jMenu2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JPanel m_CUPanel;
    private javax.swing.JMenuItem m_exitMenuItem;
    private javax.swing.JPanel m_logsPanel;
    private javax.swing.JTextArea m_logsTextArea;
    private javax.swing.JTable m_plansJTable;
    private javax.swing.JPanel m_queriesPanel;
    private javax.swing.JMenuItem m_startCoordinatorMenuItem;
    private javax.swing.JMenuItem m_stopCoordinatorMenuItem;
    private javax.swing.JMenuBar monitorJMenuBar;
    private javax.swing.JTable unitsJTable;
    // End of variables declaration//GEN-END:variables


	@Override
	public synchronized void updateLogsPanel(String str) {
		// TODO Auto-generated method stub
		if(str != null)
			m_logsTextArea.append(str + "\n");
	}

    public synchronized void updatePlansPanel(Query query) {
//        if(query.)
        DefaultTableModel plansTable = (DefaultTableModel)m_plansJTable.getModel();
        PlanState state = query.getState();
        switch(state){
            case ACCEPTED: {
                String clientId = query.getClientId();
                String planId = query.getId();
                String start = query.getStartTime();
                String finish = query.getFinishTime();
                Object[] planRow = {planId,clientId,"ACCEPTED",start,finish};
                plansTable.addRow(planRow);
                m_plansIdMap.put(planId, new Integer(m_totalPlanRows));
                m_totalPlanRows++;
                s_logger.warn("Adding plan row  state : " + state);
                break;
            }
            case ANALYZING:{
                int rowIndex = m_plansIdMap.get(query.getId());
                plansTable.setValueAt("ANALYZING", rowIndex, 2);
                break;
            }
            case DISPATCHING:{
                int rowIndex = m_plansIdMap.get(query.getId());
                plansTable.setValueAt("DISPATCHING", rowIndex, 2);
                break;
            }
            case PROCESSING:{
                int rowIndex = m_plansIdMap.get(query.getId());
                plansTable.setValueAt("PROCESSING", rowIndex, 2);
                break;
            }
            case RETURNED:{
                int rowIndex = m_plansIdMap.get(query.getId());
                plansTable.setValueAt("RETURNED", rowIndex, 2);
                plansTable.setValueAt(query.getFinishTime(), rowIndex, 4);
                break;
            }
            default: {
                s_logger.warn("Unsupported PlanState : " + state);
            }
        }
    }

    public synchronized void updateUnitsPanel(CUStub stub) {
        DefaultTableModel unitsTable = (DefaultTableModel)unitsJTable.getModel();
        String id = stub.getCUId();
        Integer rowIndexI = m_unitsIdMap.get(id);
        String planId = stub.getPlanId();
        String start = stub.getStartTime();
        String finish = stub.getFinishTime();
        String state = stub.getUnitState();
        if(rowIndexI == null){
                Object[] unitRow = {id,planId,state,start,finish};
                unitsTable.addRow(unitRow);
                m_unitsIdMap.put(id, new Integer(m_totalUnitRows));
                m_totalUnitRows++;
                return;
        }
        unitsTable.setValueAt(planId, rowIndexI, 1);
        unitsTable.setValueAt(state, rowIndexI, 2);
        unitsTable.setValueAt(finish, rowIndexI, 4);
    }


}
